/************************************************************************/
// Copyright (C) 2016, han_gangbiao. All rights reserved.
// Use of this source code is governed by a GPL-v2 license that can be found in the License file.
// 
// [Time]:      2016-1-4 21:53:17
// [Author]:    han_gangbiao [http://my.oschina.net/jackhen]
// [Info]:      
/************************************************************************/

#include "netaddr.h"

netaddr_t::netaddr_t()
{
	m_ip = (unsigned long)-1;
	m_port = 0;
	memset( &m_inet_addr, 0, sizeof(m_inet_addr) );
}

netaddr_t::netaddr_t(const char* ip, uint16 port)
{
	m_ip = (unsigned long)-1;
	m_port = 0;
	memset( &m_inet_addr, 0, sizeof(m_inet_addr) );

	set_addr(ip, port);
}

netaddr_t::netaddr_t(const struct sockaddr_in& ref_addr)
{
	m_ip = (unsigned long)-1;
	m_port = 0;
	memset( &m_inet_addr, 0, sizeof(m_inet_addr) );

	set_addr(ref_addr);
}

netaddr_t::netaddr_t(const netaddr_t& ref_other)
{
	m_ip = (unsigned long)-1;
	m_port = 0;
	memset( &m_inet_addr, 0, sizeof(m_inet_addr) );

	set_addr(ref_other.get_ipstr(), ref_other.get_port());
}

netaddr_t::~netaddr_t()
{
}

netaddr_t& netaddr_t::operator =(const netaddr_t& ref_other)
{
	if(this != &ref_other)
	{
		set_addr(ref_other.get_ipstr(), ref_other.get_port());
	}
	return *this;
}

bool netaddr_t::operator ==(netaddr_t& ref_other) const
{
	if( !is_valid() || !ref_other.is_valid() )
		return false;
	if( (m_ip == ref_other.m_ip ) && (m_port == ref_other.m_port) )
		return true;
	return false;
}

bool netaddr_t::is_valid() const
{
	if( m_ip == (unsigned long)-1 || m_port == 0 )
		return false;
	return true;
}

int netaddr_t::set_addr(const char* ip, uint16 port)
{
	if( set_ip(ip) < 0 )
		return -1;
	return set_port(port);
}

int netaddr_t::set_addr(const struct sockaddr_in& ref_addr)
{
	m_inet_addr.m_addrin = ref_addr;
	m_port = m_inet_addr.m_addrin.sin_port;
	m_ip = m_inet_addr.m_addrin.sin_addr.s_addr;
	return 0;
}

const struct sockaddr_in* netaddr_t::get_addr() const
{
	return &m_inet_addr.m_addrin;
}

int netaddr_t::get_addr_len() const
{
	return sizeof(m_inet_addr);	//union
}

int netaddr_t::set_ip(const char* ip)
{
	if( ip == NULL || ip[0] == '\0' )
		m_ip = 0;
	else if( inet_addr(ip) == INADDR_NONE )
		return -1;
	else
		m_ip = inet_addr(ip);
	m_inet_addr.m_addrin.sin_family = AF_INET;	//AF_INET
	m_inet_addr.m_addrin.sin_addr.s_addr = m_ip;

	return 0;
}

int netaddr_t::set_port(uint16 port)
{
	m_port = htons(port);
	m_inet_addr.m_addrin.sin_port = m_port;
	return 0;
}

const char* netaddr_t::get_ipstr() const
{
	struct in_addr ia;
	ia.s_addr = m_ip;
	return inet_ntoa( ia );
}

unsigned long netaddr_t::get_ip() const
{
	return ntohl( m_ip );
}

uint16 netaddr_t::get_port() const
{
	return ntohs( m_port );
}
